# -*- coding: utf-8 -*-
# <Copyright and license information goes here.>
import os
import re
from PyQt4.QtCore import Qt
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript
 
class RAIDMonitor(plasmascript.Applet):

    output = ''
    disks = ''

    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)
 
    def init(self):
        self.setHasConfigurationInterface(False)
        self.resize(125, 125)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.startTimer(60000)
 
    def paintInterface(self, painter, option, rect):
        x = 35
        y = 15

        painter.save()
        #todo draw proper output of mdstat
        painter.setPen(Qt.black)
        #painter.drawText(rect, Qt.AlignVCenter | Qt.AlignHCenter, self.output)
        painter.drawText(15, 25, self.output)
        for i in range(1, len(self.disks)-1):
            if self.disks[i] == 'U':
                painter.fillRect(i*12 + x,y,10,10, Qt.green)
            else:
                painter.fillRect(i*12 + x,y,10,10, Qt.red)


        painter.restore()
    
    def timerEvent(self, QTimerEvent):
        self.output = ''
        self.disks = ''
        f=os.popen("cat /proc/mdstat")
        #todo parse the output into only a couple of relevant variables
        for line in f.readlines():
            m = re.search("md\d", line)
            if m is not None:
                self.output += m.group(0)
            m = re.search("\[(U|_)*\]", line)
            if m is not None:
                self.disks = m.group(0)
        self.update()
 
def CreateApplet(parent):
    return HelloPython(parent)
